package com.bookyourtrek.action;

import java.sql.SQLException;
import java.util.Map;

import com.bookyourtrek.model.LoginModel;
import com.bookyourtrek.model.UserModel;
import com.bookyourtrek.util.RuntimeSettings;
import com.bookyourtrek.util.UtilityFunctions;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


/**
 * @author ananda
 * @category authentication
 */
public class LoginAction extends ActionSupport{
	
	private static final long serialVersionUID = 1L;
	
	private String email;
	private String password;
	private Boolean rememberme;		//for setting cookies
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Boolean getRememberme() {
		return rememberme;
	}
	public void setRememberme(Boolean rememberme) {
		this.rememberme = rememberme;
	}
	
	/**
	 * @return success if login is valid
	 * @throws SQLException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String login() throws SQLException {
		
		//custom validations
		LoginModel loginmodel = new LoginModel();
		
		//checking whether user exist or not
		if(!loginmodel.checkEmail(email)){
			addFieldError("email","Email does not exist.");
			return INPUT;
		}
		//check user status
		else if(loginmodel.getUserStatus(email) == RuntimeSettings.USERSTATUSBANNED){
			addFieldError("account", "Account banned");
			return INPUT;
		}
		//check user status
		else if(loginmodel.getUserStatus(email) == RuntimeSettings.USERSTATUSINACTIVE){
				addFieldError("account", "Account Inactive");
				return INPUT;
		}
		//validations ends here
		
		//if user exists and account is active then get the password, 
		//generate md5 hash and match with entered password
		else if(loginmodel.getPassword(email).equals(UtilityFunctions.generateMD5(password))) {
			Map sess=ActionContext.getContext().getSession();
			UserModel usermodel = new UserModel();
			sess.put("useremail", email);
			//System.out.println(usermodel.getUserID(email));
			sess.put("userid", usermodel.getUserID(email));
			sess.put("login", true);		
			
			//setting up cookies for 30 days
			
			return SUCCESS;
		}
		else {
			addFieldError("mismatch", "Password did not match");
			return INPUT; 
		}
	}
}
